package com.bytenebula.asteroid.controller;

import com.bytenebula.ByteNebulaException;
import com.bytenebula.asteroid.ResponseResult;
import com.bytenebula.ResultCodes;
import com.bytenebula.entity.meta.MetaColumn;
import com.bytenebula.entity.meta.MetaDatabase;
import com.bytenebula.entity.meta.MetaTable;
import com.bytenebula.asteroid.service.ExtractService;
import com.bytenebula.asteroid.service.MetaDatabaseService;
import com.bytenebula.asteroid.service.impl.ExtractServiceImpl;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Tag(name = "Extract Controller")
@RestController
@RequestMapping("/extract")
@ResponseResult
public class ExtractController {

    @Autowired
    private MetaDatabaseService databaseService;

    /**
     * 根据数据库名称抽取数据库里所有的表信息
     * @param db_name 待抽取数据库名称
     * @return 返回数据表列表
     */
    @GetMapping("/tables/db/{db_name}")
    public List<MetaTable> extractTables(@PathVariable String db_name) {
        MetaDatabase db = databaseService.getByName(db_name);
        if (db == null)
            throw new ByteNebulaException(ResultCodes.CANNOT_FIND_META_DB, db_name);
        ExtractService service = ExtractServiceImpl.createExtractService(db.getDbType());
        return service.extractTables(db_name);
    }


    /**
     * 根据数据表名称抽取列信息
     * @param db_name 带查询表所在数据库名称
     * @param table_name 待抽取数据表名称
     * @return 返回数据列列表
     */
    @GetMapping("/columns/db/{db_name}/table/{table_name}")
    public List<MetaColumn> extractColumns(@PathVariable String db_name, @PathVariable String table_name) {
        MetaDatabase db = databaseService.getByName(db_name);
        if (db == null)
            throw new ByteNebulaException(ResultCodes.CANNOT_FIND_META_DB, db_name);
        ExtractService service = ExtractServiceImpl.createExtractService(db.getDbType());
        return service.extractColumns(db_name, table_name);
    }

}
